#!/usr/bin/env python

"""Updates user guide, library and tool documentation Wiki pages.

Usage: release_update.py version

For more information, use the source Luke!
"""

from __future__ import with_statement
import re


BASE = 'http://robotframework.googlecode.com/hg'
DOC_PLACEFOLDER = '<wiki:comment>doc placefolder</wiki:comment>'
DOWNLOAD_PLACEFOLDER = '<wiki:comment>download placefolder</wiki:comment>'
LIBRARIES = { 'BuiltInLibrary.wiki': 'BuiltIn.html',
              'CollectionsLibrary.wiki': 'Collections.html',
              'DialogsLibrary.wiki': 'Dialogs.html',
              'OperatingSystemLibrary.wiki': 'OperatingSystem.html',
              'ScreenshotLibrary.wiki': 'Screenshot.html',
              'StringLibrary.wiki': 'String.html',
              'TelnetLibrary.wiki': 'Telnet.html'
            }
TOOLS = { 'ExecutionTimeReportingTool.wiki': ['times2csv', 'times2csv.html', 'times2csv.py'],
          'FileViewingTool.wiki': ['fileviewer', 'fileviewer.html', 'fileviewer.py'],
          'HistoricalReportingTool.wiki': ['ristopy', 'ristopy.html', 'risto.py'],
          'TestResultDiffingTool.wiki': ['robotdiff', 'robotdiff.html', 'robotdiff.py'],
          'TestStatusCheckerTool.wiki': ['statuschecker', 'statuschecker.html', 'statuschecker.py'],
          'OutputFileFixingTool.wiki': ['fixml', 'fixml.html', 'fixml.py'],
        }


def update(version):
    _update_doc('UserGuide.wiki', 'doc/userguide/RobotFrameworkUserGuide.html', version)
    for wiki, doc in LIBRARIES.items():
        _update_doc(wiki, 'doc/libraries/%s' % doc, version)
    for wiki, (path, doc, source) in TOOLS.items():
        _update_doc(wiki, 'tools/%s/doc/%s' % (path, doc), version)
        _update_download(wiki, 'tools/%s/%s' % (path, source), version)

def _update_doc(wiki, path, version):
    _update_wiki(wiki, path, version, DOC_PLACEFOLDER)
    print wiki

def _update_download(wiki, path, version):
    _update_wiki(wiki, path, version, DOWNLOAD_PLACEFOLDER)

def _update_wiki(wiki, path, version, placefolder):
    content = []
    placefolder_found = False
    with open(wiki) as wikifile:
        for line in wikifile:
            content.append(line)
            if line.strip() == placefolder:
                placefolder_found = True
                content.append(" * [%s/%s?r=%s Version %s]\n" %
                                (BASE, path, version, version))
    if not placefolder_found:
        print "Could not find placefolder '%s' in file '%s'" % (placefolder, wiki)
    with open(wiki, 'w') as wikifile:
        wikifile.write(''.join(content))


if __name__ == '__main__':
    import sys
    try:
        update(sys.argv[1])
    except ValueError, err:
        print err
    except:
        print __doc__

